package com.gin.kotlin.no_gay_alliance.fragment.topiclist

import android.content.Context
import android.os.Bundle
import android.os.Message
import android.util.Log
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.activity.PrivilegeActivity
import com.gin.kotlin.no_gay_alliance.activity.SubForumActivity
import com.gin.kotlin.no_gay_alliance.activity.TopicListActivity
import com.gin.kotlin.no_gay_alliance.activity.TopicListActivity.Companion.KEY_ARGUMENT
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.argument.TopicListArgument
import com.gin.kotlin.no_gay_alliance.argument.TopicListArgument.Type.USER_SEARCH
import com.gin.kotlin.no_gay_alliance.databinding.FragmentTopicListForumListBinding
import com.gin.kotlin.no_gay_alliance.enums.HandlerMessageWhat
import com.gin.kotlin.no_gay_alliance.model.SearchAreaModel
import com.gin.kotlin.no_gay_alliance.model.SubForumModel
import com.gin.nga.enums.ForumType
import com.gin.nga.enums.param.OrderByParam
import com.gin.nga.response.topic.CurrentForum

/**
 * 版面浏览
 * @property subForums 子版面信息
 */
class ForumListFragment : BaseTopicListFragment<FragmentTopicListForumListBinding>() {
    private var subForums: List<SubForumModel>? = null

    /**
     * onCreateView的后续操作 ，如通过  [FragmentActivity.addMenuProvider] 添加菜单
     */
    override fun onCreateView() {
        super.onCreateView()
        val b = this.b ?: return

        // 顶部菜单栏
        listOf(
            b.tvTopMenuBlocked,
            b.tvTopMenuSubForum,
            b.tvTopMenuRecommend,
            b.tvTopMenuTopTopic,
        ).forEach { it.setOnClickListener(this) }
    }

    /**
     * 装载菜单
     * @param menu Menu
     * @param menuInflater MenuInflater
     */
    override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
        super.onCreateMenu(menu, menuInflater)
        // 我的主题、我的回复、版面权限
        menuInflater.inflate(R.menu.topic_list_forum_list, menu)
    }

    /**
     * 菜单项点击响应
     * @param menuItem MenuItem
     * @return Boolean
     */
    override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
        return when (menuItem.itemId) {
            R.id.mi_search -> startSearch()
            R.id.mi_my_topic -> {
                TopicListActivity.startActivity(
                    requireContext(), TopicListArgument(
                        type = USER_SEARCH,
                        forumId = argument.forumId,
                        authorUid = App.INSTANCE.account.userId,
                    )
                )
                true
            }

            R.id.mi_my_reply -> {
                TopicListActivity.startActivity(
                    requireContext(), TopicListArgument(
                        type = USER_SEARCH,
                        forumId = argument.forumId,
                        authorUid = App.INSTANCE.account.userId,
                        searchReply = true,
                    )
                )
                true
            }

            R.id.mi_forum_privilege -> {
                PrivilegeActivity.start(requireContext(),argument.forumId!!)
                true

            }

            else -> super.onMenuItemSelected(menuItem)
        }
    }

    private fun startSearch(): Boolean {
        val cf = currentForum ?: return false
        // 主版面
        val searchAreas = mutableListOf(SearchAreaModel(ForumType.FORUM, cf.forumId!!, cf.forumName!!, cf.getBigIconUrl()!!, true))
        // 子版面
        cf.subForums
            ?.filter { it.type == ForumType.FORUM }
            ?.map { SearchAreaModel(ForumType.FORUM, it.id!!, it.name!!, it.getBigIconUrl()!!) }
            ?.forEach { searchAreas.add(it) }
        TopicSearchFragment.startActivityForum(requireContext(), searchAreas)
        return true
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    override fun onClick(v: View?) {
        val b = this.b ?: return
        when (v) {
            b.tvTopMenuSubForum -> {
                val id = currentForum?.forumId
                Log.i(TAG, "打开子版面列表: $id")
                subForums?.also { SubForumActivity.start(requireContext(), id!!, it) }
            }

            b.tvTopMenuRecommend -> {
                val id = currentForum?.forumId!!
                Log.i(TAG, "打开精华区: $id")
                ForumRecommendFragment.startActivity(requireContext(), id, title = currentForum?.forumName)
            }

            else -> super.onClick(v)
        }
    }

    override fun handleMessage(msg: Message): Boolean {
        when (msg.what) {
            HandlerMessageWhat.CURRENT_FORUM_UPDATE.ordinal -> {
                val currentForum = msg.obj as? CurrentForum
                this.subForums = currentForum?.subForums?.map { SubForumModel(it) }
                // 设置子版面按钮的可见性
                val size = this.subForums?.size ?: 0
                b?.tvTopMenuSubForum?.text = getString(R.string.tv_top_menu_sub_forum, size.toString())
                b?.tvTopMenuSubForum?.visibility = if (size == 0) View.GONE else View.VISIBLE
            }
        }

        return super.handleMessage(msg)
    }


    companion object {
        fun newInstance(argument: TopicListArgument) = ForumListFragment().also { it.arguments = Bundle().also { b -> b.putParcelable(KEY_ARGUMENT, argument) } }

        /**
         * 启动活动
         */
        fun startActivity(
            context: Context,
            forumId: Long,
            page: Int? = null,
            orderBy: OrderByParam? = null,
            title: String? = null
        ) = TopicListActivity.startActivity(
            context, TopicListArgument(
                TopicListArgument.Type.FORUM_LIST,
                forumId = forumId,
                page = page,
                orderBy = orderBy?.value,
                title = title
            )
        )
    }
}